package vip.xiaonuo.smzq.modular.lifecycle.service.module.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.*;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.common.util.CommonFileUtil;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.modular.lifecycle.base.KqfwCoordinates;
import vip.xiaonuo.smzq.modular.lifecycle.base.QueryLifeCycleBase;
import vip.xiaonuo.smzq.modular.lifecycle.constant.LifeCycleConstant;
import vip.xiaonuo.smzq.modular.lifecycle.constant.WebResultStatusConstant;
import vip.xiaonuo.smzq.modular.lifecycle.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.entity.view.GpKsMaxYear;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.module.CommonMapper;
import vip.xiaonuo.smzq.modular.lifecycle.po.QueryMineStorePO;
import vip.xiaonuo.smzq.modular.lifecycle.po.datamanager.*;
import vip.xiaonuo.smzq.modular.lifecycle.service.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.CommonService;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleDataManagerService;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleService;
import vip.xiaonuo.smzq.modular.lifecycle.util.CoordinateTranUtil;
import vip.xiaonuo.smzq.modular.lifecycle.util.HutoolTreeExtend;
import vip.xiaonuo.smzq.modular.lifecycle.vo.*;
import vip.xiaonuo.smzq.modular.lifecycle.vo.datamanager.CoorPolygonVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.datamanager.DBExistPedigeeMineralVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.datamanager.LifeCyclePedigeeNodeVO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <ul>
 * <li>name:  LifeCycleServiceImpl</li>
 * <li>author name: GEOSCENE_YUYANFEI</li>
 * <li>create time: 2024-03-20 15:31:25</li>
 * </ul>
 */
@Service
public class LifeCycleDataManagerServiceImpl implements LifeCycleDataManagerService {

    @Autowired
    LifeCycleService lifeCycleService;

    @Autowired
    LifeCycleMineStoreService lifeCycleMineStoreService;

    @Autowired
    LifeCyclePedigeeService lifeCyclePedigeeService;

    @Autowired
    CommonMapper commonMapper;

    @Autowired
    KclKsMapper kclKsMapper;

    @Autowired
    HisiKsMapper hisiKsMapper;

    @Autowired
    LifeCycleMineStoreMapper lifeCycleMineStoreMapper;

    @Autowired
    KclKsService kclKsService;

    @Autowired
    KclCb08XzqhService kclCb08XzqhService;

    @Autowired
    LifeCycleMineralMeaService lifeCycleMineralMeaService;

    @Autowired
    KclZbService kclZbService;

    @Autowired
    KclWjglbService kclWjglbService;

    @Autowired
    CommonService commonService;

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    LifeCyclePedigeeMapper lifeCyclePedigeeMapper;

    @Resource
    HutoolTreeExtend hutoolTreeExtend;

    @Resource
    CoordinateTranUtil coordinateTranUtil;

    @Value("${lifecycle.python.base}")
    String pythonPath;
    @Value("${lifecycle.python.createAreaImg}")
    String createAreaImgPath;
    @Value("${file.base}")
    String baseFilePath;


    /**
     * 得到查询矿山列表的wrapper
     * @param wrapperP
     * @param queryMineListPO
     * @return
     */
    @Override
    public MPJLambdaWrapper<KclKs> getKclListWrapper(MPJLambdaWrapper<KclKs> wrapperP, QueryMineListPO queryMineListPO){
        return wrapperP
                .eq(StrUtil.isNotBlank(queryMineListPO.getXkzh()),KclKs::getXkzh, queryMineListPO.getXkzh())
                .innerJoin(GpKsMaxYear.class, "gp_ks_max_year",on->
                on
                        .eq(GpKsMaxYear::getMaxnd, KclKs::getNd)
                        .eq(GpKsMaxYear::getKqbh, KclKs::getKqbh)
                        .eq(GpKsMaxYear::getDjflbh, KclKs::getDjflbh)
//                        .apply(lifeCycleService.getKsDjflbhLastThreeLSQL("t"))
                )
                .in(CollUtil.isNotEmpty(queryMineListPO.getAreaCodes()), KclKs::getXzqdm, queryMineListPO.getAreaCodes())
                .and(StrUtil.isNotBlank(queryMineListPO.getKeyword()),wrapper->
                        wrapper.like(KclKs::getKsmc,queryMineListPO.getKeyword())
                                .or()
                                .like(KclKs::getKyqr, queryMineListPO.getKeyword())
                                .or()
                                .like(KclKs::getKsbh, queryMineListPO.getKeyword())
                                .or()
                                .like(KclKs::getKqbh, queryMineListPO.getKeyword())
                                .or()
                                .apply(StrUtil.isNotBlank(queryMineListPO.getKeyword()) && NumberUtil.isNumber(queryMineListPO.getKeyword())
                                        ," t.djflbh::varchar like '%"+queryMineListPO.getKeyword()+"%' ")
                )
                .eq(ObjectUtil.isNotEmpty(queryMineListPO.getDjflbh()),KclKs::getDjflbh,queryMineListPO.getDjflbh())
                .eq(ObjectUtil.isNotEmpty(queryMineListPO.getNd()),KclKs::getNd,queryMineListPO.getNd())
                .eq(StrUtil.isNotBlank(queryMineListPO.getKqbh()),KclKs::getKqbh,queryMineListPO.getKqbh());
    }

    @Override
    public IPage<QueryMineInfoVO> queryKclKsListPage(QueryMineListPO queryMineListPO){
        Integer keyword = 0;
        if(NumberUtil.isNumber(queryMineListPO.getKeyword())){
            queryMineListPO.setNumKeyword( Convert.toInt(keyword));
        }
//        MPJLambdaWrapper<KclKs> wrapperCou = new MPJLambdaWrapper<KclKs>();
//        wrapperCou.select(KclKs::getPkid);
//        wrapperCou = getKclListWrapper(wrapperCou, queryMineListPO);
        MPJLambdaWrapper<KclKs> wrapperAll = new MPJLambdaWrapper<KclKs>()
        .selectAll(KclKs.class);
        wrapperAll = getKclListWrapper(wrapperAll, queryMineListPO);
//        wrapperAll.orderByDesc(KclKs::getNd);
//                .orderByAsc(KclKs::getKsmc);
        /*long cou = 0L;
        if(StrUtil.isNotBlank(queryMineListPO.getCurrKyq())){
            cou =kclKsMapper.selectCount(wrapperCou);
        }*/
        IPage<QueryMineInfoVO> iPage = kclKsMapper.selectJoinPage(new Page<>(queryMineListPO.getCurrentPageNum(),queryMineListPO.getPageSize()),QueryMineInfoVO.class,wrapperAll.selectAll(KclKs.class));

//        IPage<KclKs> iPage = kclKsService.page(new Page<>(queryMineListPO.getCurrentPageNum(),queryMineListPO.getPageSize()),wrapperAll).addOrder(OrderItem.asc("nd"));


        List<QueryMineInfoVO> records = iPage.getRecords();
        List<QueryMineInfoVO> queryMineInfoVOS = lifeCycleService.getKsExportType(BeanUtil.copyToList(records, QueryMineInfoVO.class));
        queryMineInfoVOS = lifeCycleService.fromTKQCopyToWKQ(queryMineInfoVOS);
        /*if(StrUtil.isNotBlank(queryMineListPO.getCurrKyq())){
            queryMineInfoVOS = queryMineInfoVOS.stream().filter(ele->StrUtil.equals(queryMineListPO.getCurrKyq(), ele.getMineObligeeType())).collect(Collectors.toList());
            long cou =kclKsMapper.selectCount(wrapperAll.select(KclKs::getPkid));
            iPage.setTotal(cou);
        }*/
//        初始化矿区类型
        queryMineInfoVOS = queryMineInfoVOS.stream().map(ele->{
            ele.initKsType();
            return ele;
        }).collect(Collectors.toList());
        iPage.setRecords(queryMineInfoVOS);
        return iPage;
    }



    public IPage<KclKs> queryKclKsListPageBak(QueryMineListPO queryMineListPO){
        Integer keyword = 0;
        if(NumberUtil.isNumber(queryMineListPO.getKeyword())){
            queryMineListPO.setNumKeyword( Convert.toInt(keyword));
        }
        LambdaQueryWrapper<KclKs> wrapperAll = new LambdaQueryWrapper<KclKs>().in(CollUtil.isNotEmpty(queryMineListPO.getAreaCodes()), KclKs::getXzqdm, queryMineListPO.getAreaCodes())
                .and(StrUtil.isNotBlank(queryMineListPO.getKeyword()),wrapper->
                                wrapper.like(KclKs::getKsmc,queryMineListPO.getKeyword())
                                        .or()
                                        .like(KclKs::getKyqr, queryMineListPO.getKeyword())
                                        .or()
                                        .like(KclKs::getKsbh, queryMineListPO.getKeyword())
                                        .or()
                                        .apply(StrUtil.isNotBlank(queryMineListPO.getKeyword()) && NumberUtil.isNumber(queryMineListPO.getKeyword())
                                                ," nd::varchar like '%"+queryMineListPO.getKeyword()+"%' or djflbh::varchar like '%"+queryMineListPO.getKeyword()+"%' ")
                );

        IPage<KclKs> iPage = kclKsService.page(new Page<>(queryMineListPO.getCurrentPageNum(),queryMineListPO.getPageSize()),wrapperAll).addOrder(OrderItem.asc("nd"));


        List<KclKs> records = iPage.getRecords();
        List<QueryMineInfoVO> queryMineInfoVOS = lifeCycleService.getKsExportType(BeanUtil.copyToList(records, QueryMineInfoVO.class));
        if(StrUtil.isNotBlank(queryMineListPO.getCurrKyq())){
            queryMineInfoVOS = queryMineInfoVOS.stream().filter(ele->StrUtil.equals(queryMineListPO.getCurrKyq(), ele.getMineObligeeType())).collect(Collectors.toList());
            long cou = kclKsService.count(wrapperAll);
            iPage.setTotal(cou);
        }
//        初始化矿区类型
        queryMineInfoVOS = queryMineInfoVOS.stream().map(ele->{
            ele.initKsType();
            return ele;
        }).collect(Collectors.toList());
        iPage.setRecords(BeanUtil.copyToList(queryMineInfoVOS,KclKs.class));
        return iPage;
    }

    @Override
    public Integer getApplyStoreNestYear(QueryLifeCycleBase queryLifeCycleBase) {
        /*List<>hisiKsMapper.selectJoinList(HisiKs.class
                ,new MPJLambdaWrapper<HisiKs>()
                .selectMax(HisiKs::getNd)
        );*/
        return null;
    }

    @Override
    @Transactional
    public boolean uploadMeterFile(List<MultipartFile> files, String id) {
        boolean result = false;
        for (MultipartFile file : files) {

            //文件名称

            String fileName = file.getOriginalFilename();
            String filePath = baseFilePath+"/lifeCycle/"+id;
            if(!FileUtil.exist(filePath)){
                FileUtil.mkdir(filePath);
            }
            File file1 = new File(filePath+"/"+ fileName);
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);//解码
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String wjName = fileName.substring(0, fileName.lastIndexOf("."));
            KclWjglb kclWjglb = new KclWjglb();
            kclWjglb.setZlscId(id);
            kclWjglb.setWjhz(suffix);
            kclWjglb.setWjmc(wjName);
            kclWjglb.setWjdx(Convert.toBigDecimal(file1.length()));
            kclWjglb.setScsj(DateUtil.now());
            kclWjglb.setWjlj(file1.getAbsolutePath());
            result = kclWjglbService.save(kclWjglb);
        }
        return result;
    }

    @Override
    public void downloadFiles(List<String> fileIds) {
//        List<String> fileIds = StrUtil.split(fileId,",");
        if(CollUtil.size(fileIds)!=0){
            List<KclWjglb> kclWjglbs = kclWjglbService.lambdaQuery().in(KclWjglb::getPkid,fileIds).list();
            List<File> files = CollUtil.newArrayList();
            if(CollUtil.size(kclWjglbs)!=0){
                for (KclWjglb kclWjglb:kclWjglbs) {
                    String wjlj = CollUtil.getFirst(kclWjglbs).getWjlj();
                    if(FileUtil.exist(wjlj)){
                        files.add(FileUtil.file(wjlj));
                    }
                }

                if(CollUtil.size(files)==1){
                    PathUtils.singleFileShow(CollUtil.getFirst(files).getPath(), response);
                }else{

                    File foFile = FileUtil.getParent(CollUtil.getFirst(files),1);
                    String foMainName = FileUtil.mainName(foFile);
                    String zipFolder = FileUtil.getParent(CollUtil.getFirst(files).getAbsolutePath(),2);
                    String zipPath = zipFolder+"\\"+foMainName+".zip";
                    CommonFileUtil.compressFilesToZip(files, zipPath);
                    PathUtils.singleFileShow(zipPath, response);

                    File file = new File(zipPath);
                    if (FileUtil.exist(file)) {
                        FileUtil.del(file);
                    }
                }

            }

        }

    }

    @Override
    public List<DBExistPedigeeMineralVO> queryDBExistPedigeeMineralList(String curMinCode) {
        MPJLambdaWrapper<LifeCyclePedigee> wrapper = new MPJLambdaWrapper<LifeCyclePedigee>()
//                .selectAs(KclKs::getKsmc, DBExistPedigeeMineralVO::getMineralName)
                .selectAs(KclKs::getKsmc, DBExistPedigeeMineralVO::getLabel)
//                .selectAs(KclKs::getKqbh, DBExistPedigeeMineralVO::getMineralCode)
                .selectAs(KclKs::getKqbh, DBExistPedigeeMineralVO::getValue)
//                .select(KclKs::getXkzh)
                .innerJoin(KclKs.class,KclKs::getKqbh, LifeCyclePedigee::getMineralCode)
                .apply(" t1.djflbh::varchar like '%00'").distinct();
//                .likeRight(KclKs::getDjflbh, "00");
//        将当前矿区放到第一个
        List<DBExistPedigeeMineralVO> dbExistPedigeeMineralVOS =lifeCyclePedigeeMapper.selectJoinList(DBExistPedigeeMineralVO.class,wrapper);
//                当前矿区
        List<DBExistPedigeeMineralVO> curMinExiPedList = dbExistPedigeeMineralVOS.stream().filter(ele->StrUtil.equals(ele.getValue(),curMinCode)).collect(Collectors.toList());
        List<DBExistPedigeeMineralVO> noCurMinExiPedList = dbExistPedigeeMineralVOS.stream().filter(ele->!StrUtil.equals(ele.getValue(),curMinCode)).collect(Collectors.toList());

        return ListUtil.toList(CollUtil.addAll(curMinExiPedList, noCurMinExiPedList));
    }

    @Override
    public List<LifeCyclePedigeeNodeVO> queryPedigeeLifeCycleNodes(String mineralCode,List<Integer> regClassCodes) {
        List<LifeCyclePedigeeNodeVO> lifeCyclePedigeeNodeVOS = lifeCyclePedigeeMapper.selectJoinList(LifeCyclePedigeeNodeVO.class
                ,new MPJLambdaWrapper<LifeCyclePedigee>()
                        .selectAs(LifeCycleMineStore::getReportName, LifeCyclePedigeeNodeVO::getNodeName)
                        .selectAs(LifeCyclePedigee::getName, LifeCyclePedigeeNodeVO::getPedNodeName)
                        .selectAs(LifeCycleMineStore::getStoreDate, LifeCyclePedigeeNodeVO::getNodeDate)
                        .selectAs(LifeCyclePedigee::getId,LifeCyclePedigeeNodeVO::getPedId)
                        .selectAs(LifeCyclePedigee::getParentId, LifeCyclePedigeeNodeVO::getPedPid)
                        .selectAs(LifeCyclePedigee::getXlIndex,LifeCyclePedigeeNodeVO::getXlIndex)
                        .select(LifeCycleMineStore::getExporeType)
                        .select(LifeCyclePedigee::getRegClassCode)
                        .leftJoin(LifeCycleMineStore.class, LifeCycleMineStore::getId, LifeCyclePedigee::getMineStoreId)
//                        .innerJoin(LifeCycleMineStore.class, LifeCycleMineStore::getId, LifeCyclePedigee::getMineStoreId)
                        .eq(LifeCyclePedigee::getMineralCode,mineralCode)
                        .in(CollUtil.isNotEmpty(regClassCodes),LifeCycleMineStore::getRegClassCode,regClassCodes)
                        .orderByAsc(LifeCycleMineStore::getRegClassCode)
                        .orderByDesc(LifeCycleMineStore::getStoreDate)
        );
        lifeCyclePedigeeNodeVOS.forEach(ele->{
            ele.init();
        });
        return lifeCyclePedigeeNodeVOS;
    }

    @Override
    public WebResultStatusConstant firstNodeToWKQ(SaveLCNodePO saveLCNodePO) {
        QueryMineStorePO queryMineStorePO = new QueryMineStorePO();
        queryMineStorePO.setRegClassCode(saveLCNodePO.getRegClassCode());
        queryMineStorePO.setMineralCode(saveLCNodePO.getMineralCode());
//        queryMineStorePO.setYear(year);
        List<QueryMineStoreVO> lcNodes = lifeCycleService.queryLCNodeList(queryMineStorePO,false);

        if(CollUtil.size(lcNodes)!=0){
            QueryMineStoreVO queryMineStoreVO = CollUtil.getFirst(lcNodes);
//            如果第一个不是无矿业权
            if(queryMineStoreVO.getExporeType() !=  Convert.toInt(LifeCycleConstant.mineTypeCodes.get(0))){
                String fD = DateUtil.format(Convert.toDate(saveLCNodePO.getStoreDate()),DatePattern.PURE_DATE_PATTERN);
                String sD = DateUtil.format(Convert.toDate(queryMineStoreVO.getStoreDate()),DatePattern.PURE_DATE_PATTERN);
//                如果当前节点时间小于第一个节点时间
                if(StrUtil.compare(fD,sD,true)>0){
                    LifeCycleMineStore lifeCycleMineStore = BeanUtil.copyProperties(queryMineStoreVO,QueryMineStoreVO.class);
                    lifeCycleMineStore.setExporeType(Convert.toInt(LifeCycleConstant.mineTypeCodes.get(0)));
                    lifeCycleMineStoreService.updateById(lifeCycleMineStore);
                    if(CollUtil.size(queryMineStoreVO.getLifeCyclePedigeeList())==0){
                        LifeCyclePedigee lifeCyclePedigee = new LifeCyclePedigee();
                        lifeCyclePedigee.setParentId(null);
                        lifeCyclePedigee.setMineStoreId(lifeCycleMineStore.getId());
                        lifeCyclePedigee.setId(getPedId(lifeCycleMineStore.getMineralCode(),lifeCycleMineStore.getRegClassCode(),lifeCycleMineStore.getStoreDate(),null));
                        lifeCyclePedigee.setRegClassCode(lifeCycleMineStore.getRegClassCode());
                        lifeCyclePedigee.setMineralCode(lifeCycleMineStore.getMineralCode());
                        lifeCyclePedigee.setYear(lifeCycleMineStore.getYear());
                        lifeCyclePedigeeService.saveOrUpdate(lifeCyclePedigee);
                    }
                }else{
                    return WebResultStatusConstant.CUR_THAN_FIRST;
                }
            }

        }else{
            return WebResultStatusConstant.CUR_THAN_FIRST;
        }

        return WebResultStatusConstant.SUCCESS_OPERATION;
    }

    private List<List<String>> getCooGroups(String coorStr){
        List<List<String>> result = CollUtil.newArrayList();
        List<String> coorStrs = StrUtil.split(coorStr,",");
//        获取所有星号的索引
        List<Integer> xIns = CollUtil.newArrayList();
        for (int i = 0; i < CollUtil.size(coorStrs); i++) {
            String ele = CollUtil.get(coorStrs,i);
            if(StrUtil.equals("*",ele)){
                xIns.add(i);
            }
        }
//    遍历所有
        for (int i = 0; i < CollUtil.size(xIns); i++) {
            Integer xIn = CollUtil.get(xIns,i);
            if(i==0){
//               第一个范围坐标点
                List<String> fCoors =CollUtil.sub(coorStrs,0,xIn);
                CollUtil.addAll(result,CollUtil.split(fCoors,3));
                List<String> xEle = CollUtil.sub(coorStrs,xIn,xIn+5);
                result.add(xEle);

            }else{
//               截取开始
                Integer start = CollUtil.get(xIns,i-1)+5;
                List<String> fCoors =CollUtil.sub(coorStrs,start,xIn);
                CollUtil.addAll(result,CollUtil.split(fCoors,3));
                List<String> xEle = CollUtil.sub(coorStrs,xIn,xIn+5);
                result.add(xEle);
            }
        }

        return result;
    }
    /**
     * 检查是否存在不是数字的情况
     * @param coorStr 坐标字符串
     * @return true/false
     */
    public boolean checkIsExNoNum(String coorStr){
        boolean result = true;
        for (List<String> cooGroup:getCooGroups(coorStr)) {
            String firstEle = StrUtil.trim(CollUtil.getFirst(cooGroup));
            String x = StrUtil.trim(CollUtil.get(cooGroup,1));
            String y = StrUtil.trim(CollUtil.get(cooGroup,2));
            if(!StrUtil.equals("*",firstEle)){
                if(!NumberUtil.isNumber(x) || !NumberUtil.isNumber(y)){
                    result = false;
                    break;
                }
            }else{
                if(!StrUtil.equalsAny(CollUtil.getLast(cooGroup),"1","-1")){
                    result = false;
                    break;
                }
            }

        }
        return result;
    }

    /**
     * 检查*号格式是否合理
     * @param coorStr 坐标字符串
     * @return
     */
    public boolean checkXingIsTrue(String coorStr){
        boolean result = true;
        List<List<String>> grps =  getCooGroups(coorStr);

        List<String> lastEle = CollUtil.getLast(grps);

        if(!StrUtil.equals("*",CollUtil.getFirst(lastEle))){
            result = false;
        }
        return result;
    }

    /**
     * 检查坐标或者范围信息是否正确
     * @param coorStr 坐标字符串
     * @return
     */
    private boolean checkCountIsTrue(String coorStr){
        boolean xTrue = true;
        boolean nxTrue = true;
        List<List<String>> grpCoors = getCooGroups(coorStr);
        List<List<String>> xList = grpCoors.stream().filter(ele->StrUtil.equals("*",CollUtil.getFirst(ele))).collect(Collectors.toList());

        List<List<String>> nxList = grpCoors.stream().filter(ele->!StrUtil.equals("*",CollUtil.getFirst(ele))).collect(Collectors.toList());

        for (List<String> xEle:xList) {
            if(CollUtil.size(xEle)!=5){
                xTrue = false;
                break;
            }
        }
        for (List<String> xEle:xList) {
            if(CollUtil.size(xEle)!=3){
                nxTrue = false;
                break;
            }
        }

        return xTrue && nxTrue;
    }

    @Override
    public String checkCoorTrue(String coorStr) {
        coorStr = handerCoorStr(coorStr);
        List<String> coorStrs = StrUtil.split(coorStr,",");
        if(checkCountIsTrue(coorStr)){
            return "请检查,必须符合坐标文本的格式";
        }else{
            if(!checkIsExNoNum(coorStr)){
                return "坐标必须是数字并且性质必须是1或-1";
            }

            if(!checkXingIsTrue(coorStr)){
                return "最后一个拐点必须是*";
            }

            return "成功";

        }
    }


//    x,y的
    public String checkCoorTrueBak(String coorStr) {
        coorStr = handerCoorStr(coorStr);
        List<String> coorStrs = StrUtil.split(coorStr,",");
        if(CollUtil.size(coorStrs)%2!=0){
            return "必须是一对一对的坐标";
        }else{
            boolean isNum = true;
            for (String coorItem:coorStrs) {
                if(!NumberUtil.isNumber(StrUtil.trim(coorItem))){
                    isNum = false;
                    break;
                }
            }
            if(!isNum){
                return "存在不是数字的坐标";
            }else{
                return "成功";
            }
        }
    }
    private String handerCoorStr(String coorStr){
        coorStr = StrUtil.trim(coorStr);
        coorStr = StrUtil.replace(coorStr,"，",",");
        if(StrUtil.endWith(coorStr,",")){
            coorStr = StrUtil.subBefore(coorStr,",",true);
        }
        coorStr = StrUtil.replace(coorStr,"\n","");

        return coorStr;
    }
    @Override
    public List<KqfwCoordinates> getCoorItemByCoorStr(String coorStr) {
        List<KqfwCoordinates> result = CollUtil.newArrayList();
        coorStr = handerCoorStr(coorStr);
        List<String> coors = StrUtil.split(coorStr,",");
        List<List<String>> coorsList = getCooGroups(coorStr);
        for (int i = 0; i < CollUtil.size(coorsList); i++) {
            List<String> coorItem = CollUtil.get(coorsList,i);
            KqfwCoordinates kqfwCoordinates = new KqfwCoordinates();
            if(StrUtil.equals("*",StrUtil.trim(CollUtil.getFirst(coorItem)))){
                kqfwCoordinates.setInflectionPoint("*");
                kqfwCoordinates.setX(StrUtil.trim(CollUtil.get(coorItem,1)));
                kqfwCoordinates.setY(StrUtil.trim(CollUtil.get(coorItem,2)));
                kqfwCoordinates.setOreBodyIdentification(StrUtil.trim(CollUtil.get(coorItem,3)));
                kqfwCoordinates.setNature(StrUtil.trim(CollUtil.getLast(coorItem)));
            }else{
                kqfwCoordinates.setInflectionPoint(Convert.toStr(i+1));
                kqfwCoordinates.setX(StrUtil.trim(CollUtil.get(coorItem,1)));
                kqfwCoordinates.setY(StrUtil.trim(CollUtil.getLast(coorItem)));
            }

            result.add(kqfwCoordinates);
        }
        return result;
    }


    public String getPedId(String mineralCode,Integer regClassCode, LocalDate localDate,Integer xlInd){
        String xlIndStr = ObjectUtil.isNotEmpty(xlInd)?Convert.toStr(xlInd):"";
        return mineralCode+"_"+regClassCode+xlIndStr+"_"+DateUtil.format(Convert.toDate(localDate),DatePattern.PURE_DATE_PATTERN);
    }


    /**
     * 更新族谱下一个节点的父id
     * @param curDateStr 当前日期字符串
     * @param prePedId 之前族谱id
     * @param mineralCode 矿区编号
     * @return true/false
     */
    private void updateNextPedNode(String curDateStr,String prePedId,String mineralCode){
//        当前生命周期时间日期字符串
        String preDataStr = CollUtil.getLast(StrUtil.split(prePedId, StrPool.C_UNDERLINE));
//        通过当前族谱节点的id，以及生命周期时间节点id,查询当前族谱节点的所有子节点，如果list不是一个，则为分立
        List<LifeCyclePedigee> list = lifeCyclePedigeeService.lambdaQuery().eq(LifeCyclePedigee::getMineralCode,mineralCode).like(LifeCyclePedigee::getParentId, prePedId).list();
//        遍历子节点
        for (LifeCyclePedigee lcp:list) {
//            将之前的时间替换成，当前的时间
            lcp.setParentId(StrUtil.replace(lcp.getParentId(),preDataStr, curDateStr));
            lifeCyclePedigeeMapper.updateById(lcp);
//            lifeCyclePedigeeService.updateById(lcp);
        }
    }

    @Override
    @Transactional
    public boolean saveOrUpdateLCNode(SaveLCNodePO saveLCNodePO) {

        boolean result = true;
        saveLCNodePO.initExporeType();
//        是否是编辑
        boolean isEdit = StrUtil.isNotBlank(saveLCNodePO.getId());
        firstNodeToWKQ(saveLCNodePO);

        CreateAreaImgPO createAreaImgPO = null;
        if(StrUtil.isBlank(saveLCNodePO.getId())){
            saveLCNodePO.setSaveTime(DateUtil.toLocalDateTime(new Date()));
        }else{

            LifeCycleMineStore lcm = lifeCycleMineStoreService.getById(saveLCNodePO.getId());




//            处理族谱节点

            if(ObjUtil.isNotEmpty(lcm)){

                /*如果是正常节点修改为新立或者新立修改为正常节点*/
                if(!StrUtil.equals(lcm.getReportName(),saveLCNodePO.getReportName())){
                    /*新立修改为正常节点*/
                    if(
                            (CollUtil.contains(LifeCycleConstant.flPedTypes, lcm.getReportName()) && !CollUtil.contains(LifeCycleConstant.flPedTypes, saveLCNodePO.getReportName()))
                                    || (CollUtil.contains(LifeCycleConstant.flPedTypes, saveLCNodePO.getReportName()) && !CollUtil.contains(LifeCycleConstant.flPedTypes, lcm.getReportName()))

                    ){
                        lifeCyclePedigeeService.remove(new LambdaQueryWrapper<LifeCyclePedigee>().eq(LifeCyclePedigee::getMineStoreId,saveLCNodePO.getId()));
                    }
                }

                if(StrUtil.isNotBlank(lcm.getMineralAreaPath())
                        && FileUtil.exist(lcm.getMineralAreaPath())
                        && lcm.getExporeType()!=saveLCNodePO.getExporeType()
                        && StrUtil.isNotBlank(lcm.getDmlCoor())
                ){
                    createAreaImgPO = createMineField(lcm.getDmlCoor(), Convert.toStr(lcm.getExporeType()), lcm.getId());
                }
            }

            //        之前的【如果是分立,或者没有族谱节点】 09-20号修改的【如果没有族谱节点】
            if(CollUtil.size(saveLCNodePO.getLifeCyclePedigeeList())==0){
//            if(saveLCNodePO.getIsDiscrete() || CollUtil.size(saveLCNodePO.getLifeCyclePedigeeList())==0){
                lifeCyclePedigeeService.remove(new LambdaQueryWrapper<LifeCyclePedigee>().eq(LifeCyclePedigee::getMineStoreId,saveLCNodePO.getId()));
            }
            saveLCNodePO.setEditTime(DateUtil.toLocalDateTime(new Date()));
        }
        LifeCycleMineStore lifeCycleMineStore = BeanUtil.copyProperties(saveLCNodePO, LifeCycleMineStore.class);
        lifeCycleMineStore.setYear(saveLCNodePO.getStoreDate().getYear());
        if(ObjUtil.isNotEmpty(createAreaImgPO)){
            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
        }
//        增加时间节点
        if(StrUtil.isBlank(lifeCycleMineStore.getId())){
            result = lifeCycleMineStoreService.save(lifeCycleMineStore);
        }else {
            result = lifeCycleMineStoreService.updateById(lifeCycleMineStore);
        }

        Console.log("入库的",JSONUtil.toJsonStr(lifeCycleMineStore));
//        将id设置进参数类中
        saveLCNodePO.setId(lifeCycleMineStore.getId());
        if(CollUtil.size(saveLCNodePO.getLifeCyclePedigeeList())!=0){
//            族谱节点id列表
            List<String> pedIds = CollUtil.newArrayList();
//            遍历族谱节点
            for (LifeCyclePedigee lifeCyclePedigee:saveLCNodePO.getLifeCyclePedigeeList()) {
                lifeCyclePedigee.setMineStoreId(lifeCycleMineStore.getId());
//                如果存在族谱节点，则删除
                if(StrUtil.isNotBlank(lifeCyclePedigee.getId())){
//                    如果是编辑,族谱节点位置保持不变
                    LifeCyclePedigee srcPed = lifeCyclePedigeeService.getById(lifeCyclePedigee.getId());
                    lifeCyclePedigee.setLocX(ObjectUtil.isNotEmpty(srcPed)?srcPed.getLocX():null);
                    lifeCyclePedigee.setLocY(ObjectUtil.isNotEmpty(srcPed)?srcPed.getLocY():null);
                    lifeCyclePedigeeService.removeById(lifeCyclePedigee.getId());
                    String prePedId = getPedId(saveLCNodePO.getMineralCode(),saveLCNodePO.getRegClassCode(),saveLCNodePO.getPreStoreDate(),lifeCyclePedigee.getXlIndex());
//                    如果时间被修改了，则需要对当前节点的子节点的父id进行更新
                    if(!ObjectUtil.equals(saveLCNodePO.getStoreDate(),saveLCNodePO.getPreStoreDate()) && isEdit){
//                        删除之前的族谱节点
                        lifeCyclePedigeeService.removeById(prePedId);
                        updateNextPedNode(
                                DateUtil.format(Convert.toDate(saveLCNodePO.getStoreDate()),DatePattern.PURE_DATE_PATTERN)
                                ,prePedId
                                ,lifeCycleMineStore.getMineralCode()
                        );
                    }


                }
//                得到族谱父id列表
                List<String> pIds = StrUtil.split(lifeCyclePedigee.getParentId(),",");
//                如果族谱存在父节点，并且是合并而来的族谱节点，并且不是分立
                if(CollUtil.size(pIds)!=1 && CollUtil.size(pIds)!=0 && ObjectUtil.isEmpty(lifeCyclePedigee.getXlIndex())){
                    lifeCyclePedigee.setType(LifeCycleConstant.zc);
                    for (String id:pIds) {
                        LifeCyclePedigee lifeCyclePedigeeParent = lifeCyclePedigeeService.getById(id);
                        lifeCyclePedigeeParent.setId(id);
                        lifeCyclePedigeeParent.setType(LifeCycleConstant.hb);
//                        如果当前族谱节点的父节点存在许可证号,并且当前族谱节点存在许可证号，父节点许可证号和当前几点许可证号不一样，则父节点不是当前族谱节点的主矿山
                        if(StrUtil.isNotBlank(lifeCyclePedigeeParent.getXkzh()) && StrUtil.isNotBlank(lifeCyclePedigee.getXkzh())
                                && !StrUtil.equals(lifeCyclePedigeeParent.getXkzh(), lifeCyclePedigee.getXkzh())
                        ){
                            lifeCyclePedigeeParent.setMainMine(false);
                        }
                        lifeCyclePedigeeService.updateById(lifeCyclePedigeeParent);
                    }
//                    设置分立类型
                }else if(ObjectUtil.isNotEmpty(lifeCyclePedigee.getXlIndex())){
                    lifeCyclePedigee.setType(LifeCycleConstant.fl);
                }else{
//                    设置正常类型
                    lifeCyclePedigee.setType(LifeCycleConstant.zc);
                }
                lifeCyclePedigeeService.saveOrUpdate(lifeCyclePedigee);
                pedIds.add(lifeCyclePedigee.getId());
            }
            List<String> pedIds1 = CollUtil.newArrayList();
            //                    处理压覆的情况
            if(StrUtil.equals(CollUtil.getFirst(LifeCycleConstant.crePedNodTypes), saveLCNodePO.getReportName())){
                pedIds1.add(CollUtil.getLast(pedIds));
                pedIds = CollUtil.newArrayList(CollUtil.getLast(pedIds));
            }

//            如果选择了下一个节点
            if(CollUtil.size(saveLCNodePO.getNextPedigeeVals())!=0){
                if(CollUtil.size(pedIds)!=0){

//                    下一个节点的id
                    String nextPedId = CollUtil.getLast(saveLCNodePO.getNextPedigeeVals());
//                    下一个节点的对象
                    LifeCyclePedigee nextLCP =  lifeCyclePedigeeService.getById(nextPedId);
//如果下一个节点没有父节点则将当前节点id列表赋值给下一个节点的父id
                    if(StrUtil.isBlank(nextLCP.getParentId())){
                        nextLCP.setParentId(CollUtil.join(pedIds,","));
                    }else{
//                        如果下一个节点有父节点，则将当前节点的id列表，追加到父下一个节点的父节点上
                        List<String> parentIds = StrUtil.split(nextLCP.getParentId(),",");
//                        如果在两个日期之间插入的节点，则将下一个节点的父id去掉
                        if(CollUtil.size(parentIds)!=0){
                            String prePedId = getPedId(saveLCNodePO.getMineralCode(),saveLCNodePO.getRegClassCode(),saveLCNodePO.getPreStoreDate(),null);
                            if(CollUtil.contains(parentIds,prePedId)){
                                parentIds = parentIds.stream().filter(ele->!StrUtil.contains(ele,prePedId)).collect(Collectors.toList());
                            }
                        }

                        for (String pedId:pedIds) {
                            if(!CollUtil.contains(parentIds,pedId)){
                                parentIds.add(pedId);
                            }
                        }
                        nextLCP.setParentId(CollUtil.join(parentIds,","));
                    }
                    lifeCyclePedigeeService.updateById(nextLCP);
                }

            }else{
//                处理如果选择的下一个节点为空的时候
                List<LifeCyclePedigee> pedigees = lifeCyclePedigeeService.lambdaQuery().like(LifeCyclePedigee::getParentId, CollUtil.join(pedIds,",")).list();
                for (LifeCyclePedigee lcp: pedigees) {
                    List<String> pareIds =StrUtil.split(lcp.getParentId(),",");
                    pareIds = pareIds.stream().filter(ele->!CollUtil.contains(pedIds1,ele)).collect(Collectors.toList());
                    lcp.setParentId(CollUtil.join(pareIds,","));
                    lifeCyclePedigeeService.updateById(lcp);
                }
            }

        }

        return result;
    }



//    @Override
//    @Transactional
    public boolean saveOrUpdateLCNodeBak(SaveLCNodePO saveLCNodePO) {

        boolean result = true;
//        是否是编辑
        boolean isEdit = StrUtil.isNotBlank(saveLCNodePO.getId());
        firstNodeToWKQ(saveLCNodePO);

        CreateAreaImgPO createAreaImgPO = null;
        if(StrUtil.isBlank(saveLCNodePO.getId())){
            saveLCNodePO.setSaveTime(DateUtil.toLocalDateTime(new Date()));
        }else{

            LifeCycleMineStore lcm = lifeCycleMineStoreService.getById(saveLCNodePO.getId());

//            处理族谱节点

            if(ObjUtil.isNotEmpty(lcm)){
                if(StrUtil.isNotBlank(lcm.getMineralAreaPath())
                    && FileUtil.exist(lcm.getMineralAreaPath())
                    && lcm.getExporeType()!=saveLCNodePO.getExporeType()
                    && StrUtil.isNotBlank(lcm.getDmlCoor())
                ){
                    createAreaImgPO = createMineField(lcm.getDmlCoor(), Convert.toStr(lcm.getExporeType()), lcm.getId());
                }
            }

            //        如果是分立,或者没有族谱节点
            if(saveLCNodePO.getIsDiscrete() || CollUtil.size(saveLCNodePO.getLifeCyclePedigeeList())==0){
                lifeCyclePedigeeService.remove(new LambdaQueryWrapper<LifeCyclePedigee>().eq(LifeCyclePedigee::getMineStoreId,saveLCNodePO.getId()));
            }
            saveLCNodePO.setEditTime(DateUtil.toLocalDateTime(new Date()));
        }
        LifeCycleMineStore lifeCycleMineStore = BeanUtil.copyProperties(saveLCNodePO, LifeCycleMineStore.class);
        lifeCycleMineStore.setYear(saveLCNodePO.getStoreDate().getYear());
        if(ObjUtil.isNotEmpty(createAreaImgPO)){
            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
        }
//        增加时间节点
        if(StrUtil.isBlank(lifeCycleMineStore.getId())){
            result = lifeCycleMineStoreService.save(lifeCycleMineStore);
        }else {
            result = lifeCycleMineStoreService.updateById(lifeCycleMineStore);
        }

        Console.log("入库的",JSONUtil.toJsonStr(lifeCycleMineStore));
//        将id设置进参数类中
        saveLCNodePO.setId(lifeCycleMineStore.getId());
        if(CollUtil.size(saveLCNodePO.getLifeCyclePedigeeList())!=0){
//            族谱节点id列表
            List<String> pedIds = CollUtil.newArrayList();
//            遍历族谱节点
            for (LifeCyclePedigee lifeCyclePedigee:saveLCNodePO.getLifeCyclePedigeeList()) {
                lifeCyclePedigee.setMineStoreId(lifeCycleMineStore.getId());
//                如果存在族谱节点，则删除
                if(StrUtil.isNotBlank(lifeCyclePedigee.getId())){
//                    如果是编辑,族谱节点位置保持不变
                    LifeCyclePedigee srcPed = lifeCyclePedigeeService.getById(lifeCyclePedigee.getId());
                    lifeCyclePedigee.setLocX(ObjectUtil.isNotEmpty(srcPed)?srcPed.getLocX():null);
                    lifeCyclePedigee.setLocY(ObjectUtil.isNotEmpty(srcPed)?srcPed.getLocY():null);
                    lifeCyclePedigeeService.removeById(lifeCyclePedigee.getId());
                    String prePedId = getPedId(saveLCNodePO.getMineralCode(),saveLCNodePO.getRegClassCode(),saveLCNodePO.getPreStoreDate(),null);
//                    如果时间被修改了，则需要对当前节点的子节点的父id进行更新
                    if(!ObjectUtil.equals(saveLCNodePO.getStoreDate(),saveLCNodePO.getPreStoreDate()) && isEdit){
//                        删除之前的族谱节点
                        lifeCyclePedigeeService.removeById(prePedId);
                        updateNextPedNode(
                                DateUtil.format(Convert.toDate(saveLCNodePO.getStoreDate()),DatePattern.PURE_DATE_PATTERN)
                                ,prePedId
                                ,lifeCycleMineStore.getMineralCode()
                        );
                    }


                }
//                得到族谱父id列表
                List<String> pIds = StrUtil.split(lifeCyclePedigee.getParentId(),",");
//                如果族谱存在父节点，并且是合并而来的族谱节点，并且不是分立
                if(CollUtil.size(pIds)!=1 && CollUtil.size(pIds)!=0 && ObjectUtil.isEmpty(lifeCyclePedigee.getXlIndex())){
                    lifeCyclePedigee.setType(LifeCycleConstant.zc);
                    for (String id:pIds) {
                        LifeCyclePedigee lifeCyclePedigeeParent = lifeCyclePedigeeService.getById(id);
                        lifeCyclePedigeeParent.setId(id);
                        lifeCyclePedigeeParent.setType(LifeCycleConstant.hb);
//                        如果当前族谱节点的父节点存在许可证号,并且当前族谱节点存在许可证号，父节点许可证号和当前几点许可证号不一样，则父节点不是当前族谱节点的主矿山
                        if(StrUtil.isNotBlank(lifeCyclePedigeeParent.getXkzh()) && StrUtil.isNotBlank(lifeCyclePedigee.getXkzh())
                            && !StrUtil.equals(lifeCyclePedigeeParent.getXkzh(), lifeCyclePedigee.getXkzh())
                        ){
                            lifeCyclePedigeeParent.setMainMine(false);
                        }
                        lifeCyclePedigeeService.updateById(lifeCyclePedigeeParent);
                    }
//                    设置分立类型
                }else if(ObjectUtil.isNotEmpty(lifeCyclePedigee.getXlIndex())){
                    lifeCyclePedigee.setType(LifeCycleConstant.fl);
                }else{
//                    设置正常类型
                    lifeCyclePedigee.setType(LifeCycleConstant.zc);
                }
                lifeCyclePedigeeService.saveOrUpdate(lifeCyclePedigee);
                pedIds.add(lifeCyclePedigee.getId());
            }
            List<String> pedIds1 = CollUtil.newArrayList();
            //                    处理压覆的情况
            if(StrUtil.equals(CollUtil.getFirst(LifeCycleConstant.crePedNodTypes), saveLCNodePO.getReportName())){
                pedIds1.add(CollUtil.getLast(pedIds));
                pedIds = CollUtil.newArrayList(CollUtil.getLast(pedIds));
            }

//            如果选择了下一个节点
            if(CollUtil.size(saveLCNodePO.getNextPedigeeVals())!=0){
                if(CollUtil.size(pedIds)!=0){

//                    下一个节点的id
                    String nextPedId = CollUtil.getLast(saveLCNodePO.getNextPedigeeVals());
//                    下一个节点的对象
                    LifeCyclePedigee nextLCP =  lifeCyclePedigeeService.getById(nextPedId);
//如果下一个节点没有父节点则将当前节点id列表赋值给下一个节点的父id
                    if(StrUtil.isBlank(nextLCP.getParentId())){
                        nextLCP.setParentId(CollUtil.join(pedIds,","));
                    }else{
//                        如果下一个节点有父节点，则将当前节点的id列表，追加到父下一个节点的父节点上
                        List<String> parentIds = StrUtil.split(nextLCP.getParentId(),",");
//                        如果在两个日期之间插入的节点，则将下一个节点的父id去掉
                        if(CollUtil.size(parentIds)!=0){
                            String prePedId = getPedId(saveLCNodePO.getMineralCode(),saveLCNodePO.getRegClassCode(),saveLCNodePO.getPreStoreDate(),null);
                            if(CollUtil.contains(parentIds,prePedId)){
                                parentIds = parentIds.stream().filter(ele->!StrUtil.contains(ele,prePedId)).collect(Collectors.toList());
                            }
                        }

                        for (String pedId:pedIds) {
                            if(!CollUtil.contains(parentIds,pedId)){
                                parentIds.add(pedId);
                            }
                        }
                        nextLCP.setParentId(CollUtil.join(parentIds,","));
                    }
                    lifeCyclePedigeeService.updateById(nextLCP);
                }

            }else{
//                处理如果选择的下一个节点为空的时候
                List<LifeCyclePedigee> pedigees = lifeCyclePedigeeService.lambdaQuery().like(LifeCyclePedigee::getParentId, CollUtil.join(pedIds,",")).list();
                for (LifeCyclePedigee lcp: pedigees) {
                    List<String> pareIds =StrUtil.split(lcp.getParentId(),",");
                    pareIds = pareIds.stream().filter(ele->!CollUtil.contains(pedIds1,ele)).collect(Collectors.toList());
                    lcp.setParentId(CollUtil.join(pareIds,","));
                    lifeCyclePedigeeService.updateById(lcp);
                }
            }

        }

        return result;
    }


    /**
     * 资料删除
     * @param lcNodeId 生命周期节点id
     */
    protected void zlDel(String lcNodeId){
        List<KclWjglb> kclWjglbList = kclWjglbService.list(new LambdaQueryWrapper<KclWjglb>().eq(KclWjglb::getZlscId,lcNodeId));
        for (KclWjglb kclWjglb:kclWjglbList) {
            kclWjglbService.delKclWjglb(kclWjglb.getPkid());
        }
        kclWjglbService.remove(new LambdaQueryWrapper<KclWjglb>().eq(KclWjglb::getZlscId,lcNodeId));
    }

    /**
     * 更新下一个族谱节点的父id
     * @param lcNodeId
     */
    protected void upNexPedPid(String lcNodeId,Integer xlIndex){
        //        更新下一个族谱节点的父id
        List<LifeCyclePedigee> list = lifeCyclePedigeeService.lambdaQuery()
                .eq(LifeCyclePedigee::getMineStoreId, lcNodeId)
                .eq(ObjectUtil.isNotEmpty(xlIndex),LifeCyclePedigee::getXlIndex,xlIndex)
                .list();
//        id列表
        List<String> pedIds = list.stream().map(ele->ele.getId()).collect(Collectors.toList());
        for (String pedId:pedIds) {
            List<LifeCyclePedigee> pedList = lifeCyclePedigeeService.lambdaQuery().like(LifeCyclePedigee::getParentId, pedId).list();
            for (LifeCyclePedigee pedigee:pedList) {
                String parentId = pedigee.getParentId();
                List<String> pedPids = StrUtil.split(parentId,",");
                pedPids = pedPids.stream().filter(ele->!StrUtil.equals(ele,pedId)).collect(Collectors.toList());
                pedigee.setParentId(CollUtil.join(pedPids,","));
                lifeCyclePedigeeService.updateById(pedigee);
            }
        }



    }

    @Override
    @Transactional
    public boolean lifeCycleNodeDel(String id,Integer xlIndex) {
        LifeCycleMineStore lcms = lifeCycleMineStoreService.getById(id);
        /*非分立删除*/
        if(ObjectUtil.isEmpty(xlIndex)){
//        if(!CollUtil.contains(LifeCycleConstant.flPedTypes,lcms.getReportName())){
            lifeCycleMineStoreService.removeById(id);
            zlDel(id);
            upNexPedPid(id,null);
            lifeCyclePedigeeService.remove(new LambdaQueryWrapper<LifeCyclePedigee>().eq(LifeCyclePedigee::getMineStoreId,id));
            lifeCycleMineralMeaService.remove(new LambdaQueryWrapper<LifeCycleMineralMea>().eq(LifeCycleMineralMea::getMineStoreId,id));
        }else{
            /*分立删除*/
            lifeCyclePedigeeService.remove(new LambdaQueryWrapper<LifeCyclePedigee>()
                    .eq(LifeCyclePedigee::getMineStoreId,id)
                    .eq(LifeCyclePedigee::getXlIndex,xlIndex)
            );
            upNexPedPid(id,xlIndex);
            List<LifeCyclePedigee> list = lifeCyclePedigeeService.lambdaQuery()
                    .eq(LifeCyclePedigee::getMineStoreId, id)
                    .list();
            if(CollUtil.isEmpty(list)){
                zlDel(id);
                lifeCycleMineralMeaService.remove(new LambdaQueryWrapper<LifeCycleMineralMea>().eq(LifeCycleMineralMea::getMineStoreId,id));
                lifeCycleMineStoreService.removeById(id);
            }

        }

        return true;
    }



    @Override
    @Transactional
    public boolean saveOrUpdateCoor(SaveOrUpdateCoorPO saveOrUpdateCoorPO) {
        LifeCycleMineStore lifeCycleMineStore = lifeCycleMineStoreService.getById(saveOrUpdateCoorPO.getId());
//        如果前端传过来的矿业权类型为空，则查询矿业权类型
        if(StrUtil.isNotBlank(saveOrUpdateCoorPO.getExporeType())){
            lifeCycleMineStore.setExporeType(Convert.toInt(saveOrUpdateCoorPO.getExporeType()));
//            saveOrUpdateCoorPO.setExporeType(Convert.toStr(lifeCycleMineStoreQuery.getExporeType()));
        }
//        创建生命周期节点实体类
//        LifeCycleMineStore lifeCycleMineStore = new LifeCycleMineStore();
//        lifeCycleMineStore.setId(saveOrUpdateCoorPO.getId());
        if(CollUtil.size(saveOrUpdateCoorPO.getKqfwCoordinatesList())!=0){
            String dmlCoor = commonService.getCoordinatesStr(saveOrUpdateCoorPO.getKqfwCoordinatesList());

            CreateAreaImgPO createAreaImgPO = createMineField(dmlCoor,saveOrUpdateCoorPO.getExporeType(), saveOrUpdateCoorPO.getId());

            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
            lifeCycleMineStore.setDmlCoor(dmlCoor);
        }else{
            if(StrUtil.equals(LifeCycleConstant.dml, saveOrUpdateCoorPO.getSaveType())){
                lifeCycleMineStore = lifeCycleMineStoreService.getById(saveOrUpdateCoorPO.getId());
                lifeCycleMineStore.setDmlCoor("");
                commonService.delFile(lifeCycleMineStore.getMineralAreaPath());
            }

        }

        if(CollUtil.size(saveOrUpdateCoorPO.getJsfwCoordinatesList())!=0){
            String calCoor = commonService.getCoordinatesStr(saveOrUpdateCoorPO.getJsfwCoordinatesList());
//            CreateAreaImgPO createAreaImgPO = createMineField(calCoor,saveOrUpdateCoorPO.getExporeType(), saveOrUpdateCoorPO.getId());
//            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
            lifeCycleMineStore.setCalCoor(calCoor);
        }else{
            if(StrUtil.equals(LifeCycleConstant.cal, saveOrUpdateCoorPO.getSaveType())){
                lifeCycleMineStore.setCalCoor("");
            }

        }

        if(CollUtil.size(saveOrUpdateCoorPO.getDlfwCoordinatesList())!=0){
            String momCoor = commonService.getCoordinatesStr(saveOrUpdateCoorPO.getDlfwCoordinatesList());
//            CreateAreaImgPO createAreaImgPO = createMineField(momCoor,saveOrUpdateCoorPO.getExporeType(), saveOrUpdateCoorPO.getId());
//            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
            lifeCycleMineStore.setMomCoor(momCoor);
        }else{
            if(StrUtil.equals(LifeCycleConstant.mom, saveOrUpdateCoorPO.getSaveType())){
                lifeCycleMineStore.setMomCoor("");
            }

        }

        if(CollUtil.size(saveOrUpdateCoorPO.getKtfwCoordinatesList())!=0){
            String expCoor = commonService.getCoordinatesStr(saveOrUpdateCoorPO.getKtfwCoordinatesList());
//            CreateAreaImgPO createAreaImgPO = createMineField(momCoor,saveOrUpdateCoorPO.getExporeType(), saveOrUpdateCoorPO.getId());
//            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
            lifeCycleMineStore.setExpCoor(expCoor);
        }else{
            if(StrUtil.equals(LifeCycleConstant.exp, saveOrUpdateCoorPO.getSaveType())){
                lifeCycleMineStore.setExpCoor("");
            }
        }

        if(CollUtil.size(saveOrUpdateCoorPO.getYffwCoordinatesList())!=0){
            String preCovCoor = commonService.getCoordinatesStr(saveOrUpdateCoorPO.getYffwCoordinatesList());
//            CreateAreaImgPO createAreaImgPO = createMineField(momCoor,saveOrUpdateCoorPO.getExporeType(), saveOrUpdateCoorPO.getId());
//            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
            lifeCycleMineStore.setPreCovCoor(preCovCoor);
        }else{
            if(StrUtil.equals(LifeCycleConstant.preCov, saveOrUpdateCoorPO.getSaveType())){
                lifeCycleMineStore.setPreCovCoor("");
            }
        }


        if(CollUtil.size(saveOrUpdateCoorPO.getTkqfwCoordinatesList())!=0){
            String expMinCoor = commonService.getCoordinatesStr(saveOrUpdateCoorPO.getTkqfwCoordinatesList());
            CreateAreaImgPO createAreaImgPO = createMineField(expMinCoor,saveOrUpdateCoorPO.getExporeType(), saveOrUpdateCoorPO.getId());
            lifeCycleMineStore.setMineralAreaPath(createAreaImgPO.getImgPath());
            lifeCycleMineStore.setExpMinCoor(expMinCoor);
        }else{
            if(StrUtil.equals(LifeCycleConstant.expMin, saveOrUpdateCoorPO.getSaveType())){
                lifeCycleMineStore = lifeCycleMineStoreService.getById(saveOrUpdateCoorPO.getId());
                lifeCycleMineStore.setExpMinCoor("");
                commonService.delFile(lifeCycleMineStore.getMineralAreaPath());
            }

        }

        if(StrUtil.equals("年报",lifeCycleMineStore.getReportName())){
            updateYearReportCoor(lifeCycleMineStore);
        }
        return lifeCycleMineStoreService.updateById(lifeCycleMineStore);
    }

    @Override
    public boolean updateYearReportCoor(LifeCycleMineStore lifeCycleMineStore) {
        KclZb kclZb = new KclZb();
        kclZb.setJszb(lifeCycleMineStore.getCalCoor());
        kclZb.setDlzb(lifeCycleMineStore.getMomCoor());
        kclZb.setKqzb(lifeCycleMineStore.getDmlCoor());
        return kclZbService.update(kclZb,
                new LambdaUpdateWrapper<KclZb>()
                        .eq(KclZb::getNd, lifeCycleMineStore.getYear())
                        .eq(KclZb::getDjflbh, lifeCycleMineStore.getRegClassCode())
                        .eq(KclZb::getKqbh,lifeCycleMineStore.getMineralCode())
        );
    }


    @Override
    public CreateAreaImgPO createMineField(String dmlCoor,String exportType,String id){
//        将创建对象转换成json字符串
//        String params = JSONUtil.toJsonStr(createAreaImgPO);
        CreateAreaImgPO createAreaImgPO = new CreateAreaImgPO();
        PolygonWgs84V0 polygonWgs84V0 = coordinateTranUtil.coordinateDisposeWKT3(dmlCoor);
        String wkt3CoorStr = polygonWgs84V0.getMultiPolygon();
        createAreaImgPO.setCoorPolygon(commonService.getMutiPointXY(wkt3CoorStr));
//        设置颜色
        createAreaImgPO.setColor(LifeCycleConstant.getMineTypeColor(exportType));
        createAreaImgPO.setImgPath(baseFilePath+"/lifeCycle/mineField/"+id+".png");

//        createMineField(createAreaImgPO);

        String resStr = RuntimeUtil.execForStr(pythonPath+" "+createAreaImgPath+" "+JSONUtil.toJsonStr(createAreaImgPO.getCoorPolygon())+" "+ createAreaImgPO.getColor() +" "+createAreaImgPO.getImgPath());
        Console.log(resStr);
        return createAreaImgPO;
    }

    @Override
    public boolean checkNodeDateExist(CheckNodeDatePO checkNodeDatePO) {
        List<Integer> regClassCodes = lifeCycleService.getQueLcRegClassCodes(checkNodeDatePO.getRegClassCode());
        long cou = lifeCycleMineStoreMapper.selectCount(
                new LambdaQueryWrapper<LifeCycleMineStore>()
                .in(LifeCycleMineStore::getRegClassCode, regClassCodes)
                .eq(LifeCycleMineStore::getMineralCode, checkNodeDatePO.getMineralCode())
                .eq(LifeCycleMineStore::getStoreDate, checkNodeDatePO.getStoreDate())
                .ne(StrUtil.isNotBlank(checkNodeDatePO.getLcNodeId()),LifeCycleMineStore::getId,checkNodeDatePO.getLcNodeId())
//                .apply(lifeCycleService.getQueryLifeCycleApplySQL("life_cycle_mine_store", checkNodeDatePO.getRegClassCode()))
        );

        return cou!=0;
    }


    @Override
    public CoorPolygonVO queryCoorByLcNodeId(String id) {
        CoorPolygonVO result= new CoorPolygonVO();
//        List<KqfwCoordinates> result = CollUtil.newArrayList();
        LifeCycleMineStore lifeCycleMineStore = lifeCycleMineStoreService.getById(id);
//        得到矿区范围坐标字符串
        if(StrUtil.isNotBlank(lifeCycleMineStore.getDmlCoor()) && !StrUtil.equals(lifeCycleMineStore.getDmlCoor(),"0,")){
            result.setDmlCoors(commonService.getKqfwCoordinates(lifeCycleMineStore.getDmlCoor()));
        }

        if(StrUtil.isNotBlank(lifeCycleMineStore.getCalCoor()) && !StrUtil.equals(lifeCycleMineStore.getCalCoor(),"0,")){
            result.setCalCoors(commonService.getKqfwCoordinates(lifeCycleMineStore.getCalCoor()));
        }

        if(StrUtil.isNotBlank(lifeCycleMineStore.getMomCoor()) && !StrUtil.equals(lifeCycleMineStore.getMomCoor(),"0,")){
            result.setMomCoors(commonService.getKqfwCoordinates(lifeCycleMineStore.getMomCoor()));
        }

        if(StrUtil.isNotBlank(lifeCycleMineStore.getExpCoor()) && !StrUtil.equals(lifeCycleMineStore.getExpCoor(),"0,")){
            result.setExpCoors(commonService.getKqfwCoordinates(lifeCycleMineStore.getExpCoor()));
        }

        if(StrUtil.isNotBlank(lifeCycleMineStore.getPreCovCoor()) && !StrUtil.equals(lifeCycleMineStore.getPreCovCoor(),"0,")){
            result.setPreCovCoors(commonService.getKqfwCoordinates(lifeCycleMineStore.getPreCovCoor()));
        }

        if(StrUtil.isNotBlank(lifeCycleMineStore.getExpMinCoor()) && !StrUtil.equals(lifeCycleMineStore.getExpMinCoor(),"0,")){
            result.setExpMinCoors(commonService.getKqfwCoordinates(lifeCycleMineStore.getExpMinCoor()));
        }

        return result;
    }



    @Override
    public CoorPolygonVO queryCoorByBaseParams(QueryLifeCycleBase queryLifeCycleBase) {
        CoorPolygonVO result = new CoorPolygonVO();
        //生命周期节点
        LifeCycleMineStore lifeCycleMineStore = lifeCycleMineStoreService.getById(queryLifeCycleBase.getLcNodeId());

//查出坐标列表
        List<KclZb> kclZbs = kclZbService.lambdaQuery()
                .eq(KclZb::getDjflbh,queryLifeCycleBase.getRegClassCode())
                .eq(KclZb::getNd,queryLifeCycleBase.getYear())
                .eq(KclZb::getKqbh, queryLifeCycleBase.getMineralCode())
                .list();

        if(CollUtil.size(kclZbs)!=0){
            KclZb kclZb = CollUtil.getFirst(kclZbs);
            //        得到矿区范围坐标字符串
            /*if(commonService.checkHasCoor(lifeCycleMineStore.getDmlCoor())){
                result.setDmlCoors(commonService.getKqfwCoordinates(kclZb.getKqzb()));
            }*/
            String dmlZbCoor = kclZb.getKqzb();
            String dmlLCCoor = lifeCycleMineStore.getDmlCoor();

            String calZbCoor = kclZb.getJszb();
            String calLCCoor = lifeCycleMineStore.getCalCoor();

            String momZbCoor = kclZb.getDlzb();
            String momLCCoor = lifeCycleMineStore.getMomCoor();

            String expLCCoor = lifeCycleMineStore.getExpCoor();
            String preCovLCCoor = lifeCycleMineStore.getPreCovCoor();
            String expMinLCCoor = lifeCycleMineStore.getExpMinCoor();

            if(commonService.checkHasCoor(dmlLCCoor)){
                result.setDmlCoors(commonService.getKqfwCoordinates(dmlLCCoor));
            }else{
                if(commonService.checkHasCoor(dmlZbCoor)){
                    result.setDmlCoors(commonService.getKqfwCoordinates(dmlZbCoor));
                }
            }

//            得到计算坐标
            if(commonService.checkHasCoor(calLCCoor)){
                result.setCalCoors(commonService.getKqfwCoordinates(calLCCoor));
            }else{
                if(commonService.checkHasCoor(calZbCoor)){
                    result.setCalCoors(commonService.getKqfwCoordinates(calZbCoor));
                }
            }
//          得到动量坐标
            if(commonService.checkHasCoor(momLCCoor)){
                result.setMomCoors(commonService.getKqfwCoordinates(momLCCoor));
            }else{
                if(commonService.checkHasCoor(momZbCoor)){
                    result.setMomCoors(commonService.getKqfwCoordinates(momZbCoor));
                }
            }
//            勘探坐标
            if(commonService.checkHasCoor(expLCCoor)){
                result.setExpCoors(commonService.getKqfwCoordinates(expLCCoor));
            }
//            压覆坐标
            if(commonService.checkHasCoor(preCovLCCoor)){
                result.setPreCovCoors(commonService.getKqfwCoordinates(preCovLCCoor));
            }

            //            探矿权坐标
            if(commonService.checkHasCoor(expMinLCCoor)){
                result.setExpMinCoors(commonService.getKqfwCoordinates(expMinLCCoor));
            }
            return result;
        }else{
            return getLCNodeCoorPolygonVO(lifeCycleMineStore);
        }

    }



    private CoorPolygonVO getLCNodeCoorPolygonVO(LifeCycleMineStore lifeCycleMineStore){
        CoorPolygonVO result = new CoorPolygonVO();
        String dmlCoor = lifeCycleMineStore.getDmlCoor();
        String calCoor = lifeCycleMineStore.getCalCoor();
        String momCoor = lifeCycleMineStore.getMomCoor();
        String expCoor = lifeCycleMineStore.getExpCoor();
        String preCovCoor = lifeCycleMineStore.getPreCovCoor();
        String expMinCoor = lifeCycleMineStore.getExpMinCoor();
        if(commonService.checkHasCoor(dmlCoor)){
            result.setDmlCoors(commonService.getKqfwCoordinates(dmlCoor));
        }
        if(commonService.checkHasCoor(calCoor)){
            result.setCalCoors(commonService.getKqfwCoordinates(calCoor));
        }
        if(commonService.checkHasCoor(momCoor)){
            result.setMomCoors(commonService.getKqfwCoordinates(momCoor));
        }
        if(commonService.checkHasCoor(expCoor)){
            result.setExpCoors(commonService.getKqfwCoordinates(expCoor));
        }
        if(commonService.checkHasCoor(preCovCoor)){
            result.setPreCovCoors(commonService.getKqfwCoordinates(preCovCoor));
        }
        if(commonService.checkHasCoor(expMinCoor)){
            result.setExpMinCoors(commonService.getKqfwCoordinates(expMinCoor));
        }
        return result;
    }

    /**
     * 得到图谱对象
     * @param saveLCNodePO 前端po
     * @param mineStoreId 时间节点id
     * @param pedId 族谱id
     * @return
     */
    private LifeCyclePedigee getLifeCyclePedigee(SaveLCNodePO saveLCNodePO,String mineStoreId,String pedId){
        LifeCyclePedigee lifeCyclePedigee = new LifeCyclePedigee();
        lifeCyclePedigee.setId(pedId);
        lifeCyclePedigee.setMineStoreId(mineStoreId);
        /*if(CollUtil.size(saveLCNodePO.getSrcPedigeeIds())!=0){
            lifeCyclePedigee.setParentId(CollUtil.join(saveLCNodePO.getSrcPedigeeIds(),","));
        }*/
        return lifeCyclePedigee;
    }



}

